/*
 * nipcManager.c
 *
 *  Created on: 24/09/2011
 *      Author: utn_so
 */
#include "nipcManager.h"

int32_t ConectarRaid (char *dirIp, char *puerto)
{
	 struct sockaddr_in socketInfo;
	 int32_t sd = socket(AF_INET, SOCK_STREAM, 0);
	 if (!(sd == 0))
	 {
		socketInfo.sin_family = AF_INET;
		socketInfo.sin_addr.s_addr = inet_addr(dirIp);
		socketInfo.sin_port = htons(atoi(puerto));
		if (connect(sd, (struct sockaddr*)&socketInfo, sizeof(socketInfo)) == 0) {


		} else {
				perror("connect");
		}
	} else{
		perror("socket");
	}



	return sd;
}

/*char *serializarNipc(uint8_t type, char* message,int32_t payloadLength)
{
	PAQUETE_NIPC_CABECERA newMessage;
	newMessage.type = type;
	newMessage.payloadlength = payloadLength;


	char *buffer =malloc(sizeof(PAQUETE_NIPC_CABECERA) + payloadLength);
	memcpy(buffer, &newMessage,sizeof(PAQUETE_NIPC_CABECERA));

	char payload[payloadLength];
	memcpy(payload,message,payloadLength);


	memcpy(buffer+sizeof(PAQUETE_NIPC_CABECERA), payload, payloadLength);

	return buffer;

}*/

char *serializarNipc(uint8_t type, char* message,int32_t payloadLength)
{
	PAQUETE_NIPC_CABECERA newMessage;
	newMessage.type = type;
	newMessage.payloadlength = payloadLength;


	char *buffer =malloc(sizeof(PAQUETE_NIPC_CABECERA) + payloadLength);
	memcpy(buffer, &newMessage,sizeof(PAQUETE_NIPC_CABECERA));
/*
	char* payload=malloc(payloadLength);
	memcpy(payload,message,payloadLength);
*/

	memcpy(buffer+sizeof(PAQUETE_NIPC_CABECERA), message, payloadLength);

	return buffer;

}

char *serializarNipcSinPayload(int32_t type,int32_t payloadLength)
{
	PAQUETE_NIPC_CABECERA newMessage;
	newMessage.type = type;
	newMessage.payloadlength = payloadLength;


	char *buffer;
	buffer =malloc(sizeof(PAQUETE_NIPC_CABECERA));
	memcpy(buffer, &newMessage,sizeof(PAQUETE_NIPC_CABECERA));


	return buffer;

}

stPedido *recibirDeSocket(int32_t socket,PAQUETE_NIPC_CABECERA *cabecera,int32_t *total)
{
	stPedido *pedido;
	pedido = (stPedido *)malloc(sizeof(stPedido));
	int32_t nbytes = 0;
	nbytes = recv(socket, pedido, cabecera->payloadlength, MSG_WAITALL);
	*total=nbytes;
	//printf("El tamanio a leer es [%d]", cabecera->payloadlength);
	//for(*total=0; *total < cabecera->payloadlength; *total+=nbytes){
	//	nbytes = recv(socket, pedido/*+*total */, cabecera->payloadlength-*total, 0);
	//}
	return pedido;
}





